package main

import (
	"flag"
	"fmt"
	"net/http"
	"os"
	"walnut/internal/router"
	"walnut/kernel"
)

var (
	Version     string
	Committor   string
	BuildTime   string
	config      string
	showVersion bool
)

func main() {
	flag.StringVar(&config, "c", "./config.json", "指定配置文件")
	flag.BoolVar(&showVersion, "v", false, "版本信息")

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "使用: %s [参数]\n", "执行程序")
		fmt.Fprintf(os.Stderr, "参数:\n")
		flag.PrintDefaults()
	}

	flag.Parse()

	var err error
	if showVersion {
		// 默认输出版本信息
		fmt.Printf("version: %s, committor by: %s, build at: %s", Version, Committor, BuildTime)
		return
	}
	// 加载配置文件
	if kernel.Conf, err = kernel.Load(config); err != nil {
		fmt.Fprintf(os.Stderr, "\033[31m加载配置文件失败（%s）\033[0m\n", err)
		os.Exit(0)
	}
	// 初始化日志
	kernel.Log, err = kernel.NewLog(kernel.Conf.Log)
	if err != nil {
		fmt.Fprintf(os.Stderr, "\033[31m初始化日志（%s）\033[0m\n", err)
		os.Exit(0)
	}
	// 初始化数据库
	kernel.DB, err = kernel.NewMySQL(kernel.Conf.MySQL)
	if err != nil {
		fmt.Fprintf(os.Stderr, "\033[31m初始化数据库（%s）\033[0m\n", err)
		os.Exit(0)
	}
	fmt.Fprintf(os.Stderr, "\033[32mServer started at %s\033[0m\n", kernel.Conf.Addr())
	if err := http.ListenAndServe(kernel.Conf.Addr(), mux()); err == nil {
		fmt.Fprintf(os.Stderr, "\033[31m启动服务失败（%s）\033[0m\n", err)
	}
}

func mux() *http.ServeMux {
	// 注册路由
	mux := http.NewServeMux()
	// 版本信息
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		kernel.JSON(w, 200, "success", map[string]any{
			"version":    Version,
			"committor":  Committor,
			"build_time": BuildTime,
			"config":     kernel.Conf,
		})
	})

	// 业务路由注册
	router.Base(mux)

	return mux
}
